//index.js
//获取应用实例
var wxpay = require('../../utils/pay.js')
var app = getApp()

Page({
  data: {
    mallName: "",
    selList: '',
    confirmOrder: {},
    curAddressData: null,//收货地址
    allCoupon: [],//所有能用的优惠券
    curCoupon: null,//当前优惠券
    hasPay: false,
    storeid: app.globalData.storeId,
    cash: 0,
    choosecash: 2,
    diningSid: 0,
    myOrderData: {},
    tableNumber: "",
    discount: 0,
    val: 100,
    vall: 0,
    MallAGid: 0
  },

  toClasses: function () {
    wx.reLaunch({
      url: '/pages/classes-list/index',
    })
  },

  //获取餐桌设置
  getDiningTable: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Restaurant/GetDiningTable?id=" + app.globalData.diningSid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            tableNumber: res.data.Data.TableNumber
          })
        }
      },
    })
  },

  //获取账户余额
  getUserCash: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/UserCash/GetUserCash?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cash: res.data.Data.Cash
          })
        }
      }
    })
  },

  onShow: function (e) {
    var that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      this.confirmOrder();
      this.getUserCash();
      this.getDiningTable();
      this.getMallAGid();
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  onLoad: function (e) {
    var that = this;
    var mallName = wx.getStorageSync('mallName')
    if (mallName) {
      that.setData({ mallName: mallName });
    }
  },

  confirmOrder: function (e) {
    wx.showLoading();
    var that = this;
    var said = 0;
    if (that.data.curAddressData) {
      said = that.data.curAddressData.SAId;
    }
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,
      Sid: app.globalData.diningSid,
      SelList: that.data.selList
    }
    //初始化优惠券
    wx.request({
      url: app.globalData.host + '/api/order/GetValidCouponList',
      data: {
        selList: that.data.selList,
        uid: app.globalData.userInfo.Uid
      }, // 设置请求的 参数
      success: (res) => {
        if (res.data.Code != 0) {
          return;
        }
        that.setData({
          allCoupon: res.data.Data,
          curCoupon: res.data.Data[0] ? res.data.Data[0] : 0
        });
      }
    })
    //初始化订单
    wx.request({
      url: app.globalData.host + '/api/order/SessionConfirmOrder',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0 & that.data.hasPay == false) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        }
        that.setData({
          hasPay: true
        });
        //订单确认成功
        if (res.data.Data != null) {
          var confirm = that.processImageHost(res.data.Data);
          var CartProductList = confirm.StoreOrderList[0].StoreCartInfo.CartProductList
          for (var i = 0; i < CartProductList.length; i++) {
            CartProductList[i].Selectedimg = true;
          }
        }
        if (res.data.Data == null) {
          that.setData({
            confirmOrder: {}
          });
        } else {
          that.setData({
            confirmOrder: confirm
          });
        }
      }
    })
  },

  processImageHost: function (cart) {
    if (cart.StoreOrderList.length > 0) {
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartProductList.length; i++) {
        //主图
        cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg;
        if (cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length > 0) {
          for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length; j++) {
            //赠品图片
            cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg;
          }
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg;
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartSuitList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg;
        }
      }
    }
    return cart;
  },

  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetDefaultShipAddress',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: (res) => {
        if (res.data.Code == 0) {
          that.setData({
            curAddressData: res.data.Data
          });
        }
      }
    })
  },

  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index?said=0"
    })
  },

  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },

  selectCoupon: function () {
    wx.navigateTo({
      url: "/pages/member/coupon/index?st=1&sl=" + this.data.selList
    })
  },

  getMallAGid: function () {
    var MallAGid = app.globalData.userInfo.MallAGid
    this.setData({
      MallAGid: MallAGid
    })
  },

  //删除购物车商品
  delItem: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var pid = e.currentTarget.dataset.pid;
    var t = e.currentTarget.dataset.type;//移动类型0：普通商品1：满减商品,3:组合
    if (t == 1) {
      var pindex = e.currentTarget.dataset.pindex;
      list = cart.StoreCartList[0].CartFullCutList[parseInt(pindex)].FullCutCartProductList;
    } else if (t == 2) {
      var pindex = e.currentTarget.dataset.pindex;
      list = cart.StoreCartList[0].CartFullSendList[parseInt(pindex)].FullSendMainCartProductList;
    }
    else if (t == 3) {
      return;
    }
    var MallAGid = that.data.MallAGid
    if (MallAGid > 3) {
      var DelSession = '/api/Cart/DelSessionProductByStoreAdmin'
    }
    else {
      var DelSession = '/api/cart/DelSessionProduct'
    }
    wx.request({
      url: app.globalData.host + DelSession,//删除购物车
      data: {
        pid: pid,
        sid: app.globalData.diningSid,
        selList: ""
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.confirmOrder()
        } else {
          wx.showToast({
            title: '系统错误',
            content: res.data.Message
          })
        }
      }
    })
  },

  //勾选对应的商品
  selectPid: function (e) {
    var pid = e.currentTarget.dataset.pid;
    var confirmOrder = this.data.confirmOrder
    var CartProductList = confirmOrder.StoreOrderList[0].StoreCartInfo.CartProductList
    for (var i = 0; i < CartProductList.length; i++) {
      if (pid == CartProductList[i].OrderProductInfo.Pid) {
        if (CartProductList[i].Selectedimg) {
          CartProductList[i].Selectedimg = false;
        } else {
          CartProductList[i].Selectedimg = true;
        }
        break;
      }
    }
    this.setData({
      confirmOrder: confirmOrder
    })
    this.inDiscount()
  },

  //显示折扣inDiscount
  inDiscount: function (e) {
    if (e) {
      var val = e.detail.value
      if (val == "" || val > 100) {
        var val = 100
      }
      this.setData({
        val: val
      })
    } else {
      var val = this.data.val
    }
    var confirmOrder = this.data.confirmOrder;
    var CartProductList = confirmOrder.StoreOrderList[0].StoreCartInfo.CartProductList;
    confirmOrder.AllSelectAmount = 0;
    confirmOrder.AllDiscount = 0;
    confirmOrder.realPayAmount = 0;
    console.log(CartProductList)
    for (var i = 0; i < CartProductList.length; i++) {
      if (CartProductList[i].Selectedimg) {
        confirmOrder.AllSelectAmount += parseFloat(CartProductList[i].OrderProductInfo.DiscountPrice) * parseInt(CartProductList[i].OrderProductInfo.BuyCount)//商品总计
      }
    }
    confirmOrder.AllDiscount = (parseFloat(confirmOrder.AllSelectAmount) * (1 - val / 100)).toFixed(2)//折扣金额
    confirmOrder.realPayAmount = (parseFloat(confirmOrder.AllProductAmount) - parseFloat(confirmOrder.AllDiscount)).toFixed(2)//实际付款
    this.setData({
      confirmOrder: confirmOrder,
      discount: confirmOrder.AllDiscount,
      vall: 0
    })
  },

  //确认结算订单
  createOrder: function (e) {
    var that = this;
    wx.showLoading({
      title: '提交中',
    })
    var formRemark = e.detail.value.remark || ""//备注
    var confirmOrder = this.data.confirmOrder
    var CartProductList = confirmOrder.StoreOrderList[0].StoreCartInfo.CartProductList
    confirmOrder.pids = ""
    for (var i = 0; i < CartProductList.length; i++) {
      if (CartProductList[i].Selectedimg) {
        confirmOrder.pids += CartProductList[i].OrderProductInfo.Pid + ","
      }
    }
    confirmOrder.pids = (confirmOrder.pids).substring(0, (confirmOrder.pids).length - 1)
    if (!confirmOrder.AllDiscount) {
      confirmOrder.AllDiscount = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Cart/SetSessionDiscount?storeId=' + app.globalData.storeId + '&sid=' + app.globalData.diningSid + '&discount=' + confirmOrder.AllDiscount,
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        } else {
          wx.showModal({
            title: '提示',
            content: '订单确认成功！',
            showCancel: false
          })
        }
      }
    })
  },

  //手输金额
  getDiscountVule: function (e) {
    var zongjia = this.data.confirmOrder.AllOrderAmount
    var confirmOrder = this.data.confirmOrder
    var vall = e.detail.value
    if (vall > zongjia) {
      wx.showModal({
        title: '提示',
        content: '最终折扣金额大于原订单金额',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      vall = zongjia
    }
    if (vall == '') {
      vall = zongjia
    }
    var discount = (zongjia - vall).toFixed(2)
    if (discount < 0) {
      discount = 0
    }
    confirmOrder.AllDiscount = discount
    this.setData({
      discount: discount,
      vall: vall,
      confirmOrder: confirmOrder
    })
  },

  //当输入金额大于总金额返回最大金额
  bindReplaceInput: function (e) {
    var zongjia = this.data.confirmOrder.AllOrderAmount
    var value = e.detail.value
    if (value > zongjia) {
      wx.showModal({
        title: '提示',
        content: '最终折扣金额大于原订单金额',
        showCancel: false
      })
      return {
        value: zongjia
      }
    }
    if (value < 0) {
      return {
        value: 0
      }
    }
  },

  //当输入折扣判断
  bindDiscountInput: function (e) {
    var value = e.detail.value
    if (value < 0) {
      return {
        value: ""
      }
    }
  },
  
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    var that = this;
    wx.showLoading({
      title: '正在刷新',
      success: function () {
        that.confirmOrder()
      }
    })
    wx.stopPullDownRefresh();
  }
})
